package com.study.lxy.mutithread;

import java.util.Vector;
import java.util.concurrent.Semaphore;

/**
 * 此处证明了Vector也不是绝对的线程安全
 * java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 9
 * 	at java.util.Vector.get(Vector.java:751)
 * 	at com.study.lxy.mutithread.VectorTest.lambda$main$1(VectorTest.java:30)
 * 	at java.lang.Thread.run(Thread.java:748)
 */
public class VectorTest {

    private static Vector<Integer> vector = new Vector<>();
    private static volatile boolean stop = false;
    public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(20);

        while (!stop){
            // 给Vector插入元素
            for (int i = 0; i < 10; i++) {
                vector.add(i);
            }
            // 给Vector删除元素
            Thread removeThread = new Thread(() -> {
                for (int i = 0; i < vector.size() ; i++) {
                    vector.remove(i);
                }
            });

            // 打印Vector
            Thread printThread = new Thread(() -> {
                for (int i = 0; i < vector.size() ; i++) {
                    try {
                        System.out.println(vector.get(i));
                    } catch (Exception e){
                        e.printStackTrace();
                        stop = true;
                        throw e;
                    }
                }
            });
            removeThread.start();
            printThread.start();
            while (Thread.activeCount() > 20);
        }
    }

}
